package org.robot.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@SuppressWarnings("serial")
public class StrUtils implements java.io.Serializable {

	private final static String DEFAULT_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
	public static boolean testAfterMail(String email) {
		if (!email.contains("@"))
			return false;
		return email.substring(email.indexOf("@")).matches("@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
	}

	/**
	 * 格式化当前时间
	 * 
	 * @return 1921-05-01 13:12:12
	 */
	public static String getCurrentDateTime() {
		return getCurrentDateTime(DEFAULT_TIME_PATTERN);
	}

	/**
	 * 格式化当前时间
	 * 
	 * @return 1921-05-01 13:12:12
	 */
	public static String getCurrentDateTime(String pattern) {
		java.text.SimpleDateFormat sd = new java.text.SimpleDateFormat(pattern);
		return sd.format(new java.util.Date());
	}

	/**
	 * 格式化当前时间
	 * 
	 * @param pattern
	 *            格式化(yyyy-MM-dd)
	 * @param addDay
	 *            在当前时间添加的天数
	 * @return
	 */
	public static String getCurrentDateTime(String pattern, int addDay) {
		java.text.SimpleDateFormat sd = new java.text.SimpleDateFormat(pattern);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new java.util.Date());
		calendar.add(Calendar.DAY_OF_YEAR, addDay);
		return sd.format(calendar.getTime());
	}
	
	/**
	 * 格式化当前时间
	 * 
	 * @param pattern
	 *            格式化(yyyy-MM-dd)
	 * @param addDay
	 *            在当前时间添加的小时
	 * @return
	 */
	public static String getCurrentDateTime1(String pattern, int addHour) {
		java.text.SimpleDateFormat sd = new java.text.SimpleDateFormat(pattern);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new java.util.Date());
		calendar.add(Calendar.HOUR_OF_DAY, addHour);
		return sd.format(calendar.getTime());
	}

	/**
	 * 格式化当前时间
	 * 
	 * @param addDay
	 *            在当前时间添加的天数
	 * @return
	 */
	public static String getCurrentDateTime(int addDay) {
		java.text.SimpleDateFormat sd = new java.text.SimpleDateFormat(DEFAULT_TIME_PATTERN);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new java.util.Date());
		calendar.add(Calendar.DAY_OF_YEAR, addDay);
		return sd.format(calendar.getTime());
	}

	/**
	 * 格式化当前时间
	 * 
	 * @return 1921-05-01 13:12:12
	 */
	public static String getCurrentDateTime(Date date, String pattern) {
		java.text.SimpleDateFormat sd = new java.text.SimpleDateFormat(pattern);
		return sd.format(date);
	}

	/**
	 * 根据key 获取本地配置
	 * 
	 * @param key
	 * @return
	 */
	public static String getStringByKey(String key, String properties) {
		try {
			InputStream inputStream = new FileInputStream(properties);
			Properties p = new Properties();
			p.load(inputStream);
			String str = p.getProperty(key);
			p.clear();
			inputStream.close();
			return str;
		} catch (MissingResourceException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 根据key 添加一项
	 * 
	 * @param key
	 * @return
	 */
	public static void putStringByKey(String key, String value, String properties) {
		try {
			InputStream inputStream = new FileInputStream(getWebInfPath() + properties);
			Properties p = new Properties();
			p.load(inputStream);
			inputStream.close();

			p.setProperty(key, value);
			File file = new File(getWebInfPath() + properties);
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream output = new FileOutputStream(getWebInfPath() + properties);
			p.store(output, null);
			output.close();
		} catch (MissingResourceException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String getWebInfPath() {
		URL url = StrUtils.class.getProtectionDomain().getCodeSource().getLocation();
		String path = url.toString();
		// int index = path.indexOf("WEB-INF");
		int index = path.indexOf("classes");

		if (index == -1) {
			index = path.indexOf("bin");
		}

		path = path.substring(0, index);

		if (path.startsWith("zip")) {// 当class文件在war中时，此时返回zip:D:/...这样的路径
			path = path.substring(4);
		} else if (path.startsWith("file")) {// 当class文件在class文件中时，此时返回file:/D:/...这样的路径
			path = path.substring(6);
		} else if (path.startsWith("jar")) {// 当class文件在jar文件里面时，此时返回jar:file:/D:/...这样的路径
			path = path.substring(10);
		}
		try {
			path = URLDecoder.decode(path, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return path + "properties/";
	}

	/**
	 * sql 语句 in 拼接
	 * 
	 * @param ids
	 * @param format
	 * @return
	 */
	public static String getFormatSql(Object[] ids, String format) {
		StringBuffer sb = new StringBuffer();
		sb.append("(");
		for (Object i : ids) {
			sb.append(i.toString()).append(format);
		}
		sb.append(")");
		return sb.deleteCharAt(sb.length() - 2).toString();
	}

	/**
	 * 拼接
	 * 
	 * @param ids
	 * @param format
	 * @return
	 */
	public static String getFormatObject(Object[] ids, String format) {
		StringBuffer sb = new StringBuffer();
		for (Object i : ids) {
			sb.append(i.toString()).append(format);
		}
		return sb.deleteCharAt(sb.length() - 2).toString();
	}

	/**
	 * 字符串转字数
	 * 
	 * @param ids
	 * @param match
	 *            分隔符
	 * @return
	 */
	public static Long[] convertArrayStringToLong(String ids, String match) {
		if (ids == null || ids.trim().equals(""))
			return null;
		try {
			String[] sids = ids.trim().split(match);

			Long[] lIds = new Long[sids.length];

			for (int i = 0; i < lIds.length; i++) {
				lIds[i] = Long.valueOf(sids[i].trim());
			}
			return lIds;
		} catch (NumberFormatException e) {
			return null;
		}
	}

	/**
	 * 字符串转字数
	 * 
	 * @param ids
	 * @param match
	 *            分隔符
	 * @return
	 */
	public static String[] convertArrayStringToString(String ids, String match) {
		if (ids == null || ids.trim().equals(""))
			return new String[0];
		try {
			String[] sids = ids.trim().split(match);
			return sids;
		} catch (NumberFormatException e) {
			return new String[0];
		}
	}

	/**
	 * 将任何形式的字符串转成数字
	 * 
	 * @param str
	 * @return
	 */
	public static int convertNumber(String str) {
		if (str == null || "".equals(str.trim()))
			return 0;

		str = str.trim().replaceAll("[^0-9]", "");

		if ("".equals(str.trim()))
			return 0;

		return Integer.valueOf(str);
	}

	/**
	 * 处理 特刊标识
	 * 
	 * @param str
	 * @return
	 */
	public static int convertNumberSpecial(String str) {
		try {
			if (str == null || "".equals(str.trim()))
				return 0;

			if ("".equals(str.trim()))
				return 0;
			// 处理特刊前面遇到的两个数字
			int countNum = 0;
			String tempStr = "";
			for (int i = 0; i < str.length(); i++) {
				char c = str.charAt(i);
				// 48:'0' 57:'9'
				if (c >= 48 && c <= 57) {
					countNum++;
					tempStr += c;
				}
				// 前三个数字有效, 超过20字符表示表示没有数字
				if (countNum >= 3 || i >= 20) {
					break;
				}
			}
			if (countNum == 0) {
				tempStr = "0";
			}

			return Integer.valueOf(tempStr);
		} catch (NumberFormatException e) {
			return 0;
		}
	}

	/**
	 * 查找字符串是否存在于数组
	 * 
	 * @param str
	 * @param strs
	 * @return
	 */
	public static int arryContains(Object str, Object[] strs) {
		if (str == null || strs == null || str.toString().length() == 0)
			return -1;
		for (int i = 0; i < strs.length; i++) {
			if (strs[i].toString().equalsIgnoreCase(str.toString())) {
				return i;
			}
		}
		return -1;
	}

	/**
	 * 检查是否是数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumber(Object str) {
		try {
			Long.parseLong(str.toString().trim());
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * 得到数字所表示大写字母A-
	 * 
	 * @return
	 */
	public static List<String> getLetters(int maxNum) {
		List<String> letters = new ArrayList<String>(20);
		for (int i = 65; i <= maxNum; i++) {
			String s = (char) i + "";
			letters.add(s);
		}
		return letters;
	}

	/**
	 * 正则匹配返回符合条件数据集合
	 * 
	 * @param sb
	 * @param pattern
	 * @return
	 */
	public static List<String> matcherBuffered(StringBuffer sb, String pattern) {
		if (sb == null) {
			return null;
		}
		Pattern pp = Pattern.compile(pattern);
		Matcher mm = pp.matcher(sb);

		List<String> patList = new ArrayList<String>();

		while (mm.find()) {
			patList.add(mm.group());
		}
		if (patList.size() == 0) {
			return null;
		}
		return patList;
	}

	/**
	 * 正则匹配返回符合条件字符串
	 * 
	 * @param sb
	 * @param pattern
	 * @return
	 */
	public static String matcherBuffer(StringBuffer sb, String pattern) {
		List<String> patList = matcherBuffered(sb, pattern);
		if (patList == null || patList.size() == 0)
			return "";
		return patList.get(0);
	}

	/**
	 * and条件不能为null 不能为 "" ，存在返回true
	 * 
	 * @param objects
	 * @return
	 */
	public static boolean notNullnotEmpty(Object... objects) {
		if (objects.length == 0)
			return true;

		for (int i = 0; i < objects.length; i++) {
			if (objects[i] == null)
				return true;
			if (objects[i] instanceof java.lang.String && objects[i].toString().trim().equals("")) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 时间比较 data1 在data2之前
	 */
	public static boolean compareDate(String date1, String date2) {
		if (date1 == null || "".equals(date1.trim()) || date2 == null || "".equals(date2.trim())) {
			return false;
		}
		try {
			java.text.DateFormat dateformat = new java.text.SimpleDateFormat("yyyy-MM-dd");
			// 只获取年月日

			java.util.Date timeMy = dateformat.parse(date1);
			java.util.Date timeNow = dateformat.parse(date2);

			// 当天不过期
			if (timeMy.compareTo(timeNow) == 0) {
				return true;
			} else if (timeMy.compareTo(timeNow) < 0) {
				return true;
			} else {
				return false;
			}
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 字符串转ascii
	 * 
	 * @param str
	 * @return
	 */
	public static String convertStringToAscii(String str) {
		try {
			if (str == null || str.trim().equals("")) {
				return "";
			}

			String ascii = "";
			for (int i = 0; i < str.length(); i++) {
				ascii += ((int) str.charAt(i) + ",");
			}
			ascii = ascii.substring(0, ascii.length() - 1);
			return ascii;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 转ascii字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String convertAsciiToString(String str) {
		try {
			if (str == null || str.trim().equals("")) {
				return "";
			}
			String[] asciiArrys = convertArrayStringToString(str, ",");
			String strChar = "";
			for (int i = 0; i < asciiArrys.length; i++) {
				strChar += ((char) Integer.parseInt(asciiArrys[i]));
			}
			return strChar;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String toString(Object object) {
		if (object == null) {
			return "";
		} else {
			return object.toString();
		}
	}
	
	public static String generateFileName(String fileFileName){
		int random = new Random().nextInt(10000); // 保证4位数
		if (random <= 999) {
			random = random + 1000;
		}
		int position = fileFileName.lastIndexOf(".");
		String extension = fileFileName.substring(position);
		return  StrUtils.getCurrentDateTime("yyyyMMddHHmmss")  + "-" + random + extension;
	}
	public static Map<Long, Long> analyzeFailServer(List<String> list) {
		Map<Long, Long> map = new HashMap<Long, Long>();
		try {
			for (String string : list) {
				String[]ss=string.split("-");
				long status=Long.parseLong(ss[1]);
				if(status==1){
					String strs[]=ss[0].split(";");
					for (int i=0;i<strs.length-1;i++) {
						Long serverId = Long.parseLong(strs[i]);
						if (map.containsKey(serverId)) {
							map.put(serverId, map.get(serverId) + 1);
						} else {
							map.put(serverId, 1L);
						}
					}	
				}else{
					for (String str : ss[0].split(";")) {
						Long serverId = Long.parseLong(str);
						if (map.containsKey(serverId)) {
							map.put(serverId, map.get(serverId) + 1);
						} else {
							map.put(serverId, 1L);
						}
					}	
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 格式化期刊名
	 * @return
	 */
	public static String formatJournal(String shortName){
		String journalShortName = "";
		if(shortName.indexOf("HANS_")>-1){
			//journalShortName = shortName.replace("HANS_", "").toLowerCase();
			journalShortName =  shortName.split("_")[1].toLowerCase();
			return journalShortName;
		}else if(shortName.indexOf("CONF_")>-1){
			journalShortName = shortName.replace("CONF_", "").toLowerCase();
			return journalShortName;
		}else if(shortName.indexOf("_")>-1){
			journalShortName = shortName.split("_")[0].toLowerCase();
			return journalShortName;
		}else{
			return shortName.toLowerCase();
		}
	}
	
	/**
	 * Double类型保留两位小数
	 * @author tc
	 * @date 2013-7-31
	 * @param number 需要转换的数字
	 */
	public static String getFormatDouble(double number){
		try {
			DecimalFormat df=new DecimalFormat("0.00");
			return df.format(number);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 计算两日期相隔天数
	 * @author tc
	 * @date 2013-8-5
	 * @param firstString 开始时间
	 * @param secondString 结束时间
	 */
    public static int getDaysBetween(String firstString, String secondString) {
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date firstDate = null;
			Date secondDate = null;
			try {
				firstDate = df.parse(firstString);
				secondDate = df.parse(secondString);
			} catch (Exception e) {
				// 日期型字符串格式错误
//				System.out.println("日期型字符串格式错误");
			}
			int nDay = (int) ((secondDate.getTime() - firstDate.getTime()) / (24 * 60 * 60 * 1000));
			return nDay;
		} catch (Exception e) {
			return 0;
		}
	} 
    /**
	 * 过虑xml的无效字符
     * 0x00 - 0x08
     * 0x0b - 0x0c
     * 0x0e - 0x1f
	 * @author hf
	 * @date 2014-6-16
	 */
	public static String filterStr(String xmlStr) { 
		try{
			if(null == xmlStr || "".equals(xmlStr.trim())){
				return "";
			}
	        StringBuilder sb = new StringBuilder();  
	        char[] chs = xmlStr.toCharArray();  
	        for(char ch : chs) {
	            if((ch >= 0x00 && ch <= 0x08)  
	                || (ch >= 0x0b && ch <= 0x0c)  
	                || (ch >= 0x0e && ch <= 0x1f)) {  
	            } else {
	                sb.append(ch);  
	            }  
	        }  
	        return sb.toString();  
		}catch (Exception e) {
			e.printStackTrace();
			return xmlStr;
		}
    } 
	
    public static String checkValueIsNull(String str){
    	if(str==null){
    		return "";
    	}else{
    		return str;
    	}
    }
   
    /**
     * @author xl
     * 获取字符串中第一个的年份 
     * 
     */
	public static String getYear(String string){
		
		String year="";
		String regex = "\\d{4}";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(string);
		if(m.find()) {
		return m.group();
		
		}
		
		return null;
	}
	
	  /**
     * @author xl
     * 获取字符串中第一个的年份 
     * 
     */
	public static String getIssn(String string){
		
		String year="";
		String regex = "\\d{4}\\-\\d{4}";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(string.replace(" ", ""));
		if(m.find()) {
		return m.group();
		
		}
		
		return null;
	}
	
	public static String getUUID(){    
      String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");    
      return uuid;    
  }  
	/**
	 * 字符串转时间戳
	 * @param pTime
	 * @return
	 */
	public static Timestamp str2Timestamp(String pTime){
		Date date = null;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			date = simpleDateFormat.parse(pTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
		}
		Timestamp _birthdayTimestamp = new Timestamp(date.getTime());
		return _birthdayTimestamp;
	}
	public static void main(String[] args) {
		System.out.println(System.currentTimeMillis());
		
		
	}
}
